package jpa.factory;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import jpa.dao.DAO;
import jpa.dao.JPACategoriaDAO;
import jpa.dao.JPAClienteDAO;
import jpa.dao.JPADepartamentoDAO;
import jpa.dao.JPAEnderecoDAO;
import jpa.dao.JPAEntregaDAO;
import jpa.dao.JPAFornecedorDAO;
import jpa.dao.JPAItemDAO;
import jpa.dao.JPANotaFiscalDAO;
import jpa.dao.JPAProdutoDAO;
import jpa.model.Categoria;
import jpa.model.Cliente;
import jpa.model.Departamento;
import jpa.model.Endereco;
import jpa.model.Entrega;
import jpa.model.Fornecedor;
import jpa.model.Item;
import jpa.model.NotaFiscal;
import jpa.model.Produto;

public class JPADAOFactory extends DAOFactory {

	private EntityManagerFactory factory;

	private static JPADAOFactory instance = new JPADAOFactory();

	private JPADAOFactory() {
		factory = this.openConnection();
	}

	public static JPADAOFactory getInstance() {
		return instance;
	}

	@SuppressWarnings("unchecked")
	public <T> T getFactory() {
		return (T) factory;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T openConnection() {
		if (factory == null) {
			factory = Persistence
					.createEntityManagerFactory("comercio-eletronico");

		}
		return (T) factory;
	}

	@Override
	public <T> void closeConnection(T connection) {
		if (connection instanceof EntityManagerFactory) {
			factory = (EntityManagerFactory) connection;
			if (factory != null && factory.isOpen())
				factory.close();
		}
	}

	@Override
	public DAO<Categoria> getCategoriaDAO() {
		return new JPACategoriaDAO();
	}

	public DAO<Cliente> getClienteDAO() {
		return new JPAClienteDAO();
	}

	@Override
	public DAO<Departamento> getDepartamentoDAO() {
		return new JPADepartamentoDAO();
	}

	@Override
	public DAO<Endereco> getEnderecoDAO() {
		return new JPAEnderecoDAO();
	}

	@Override
	public DAO<Entrega> getEntregaDAO() {
		return new JPAEntregaDAO();
	}

	@Override
	public DAO<Fornecedor> getFornecedorDAO() {
		return new JPAFornecedorDAO();
	}

	@Override
	public DAO<Item> getItemDAO() {
		return new JPAItemDAO();
	}

	@Override
	public DAO<NotaFiscal> getNotaFiscalDAO() {
		return new JPANotaFiscalDAO();
	}

	@Override
	public DAO<Produto> getProdutoDAO() {
		return new JPAProdutoDAO();
	}
}
